package com.shiwaixiangcun.monitor.config;

import com.shiwaixiangcun.monitor.utils.NumberGenerator;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.config.MethodInvokingFactoryBean;
import org.springframework.boot.autoconfigure.cache.CacheManagerCustomizer;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;

import javax.persistence.EntityManagerFactory;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by SilentWu on 2017/3/14.
 */
@Configuration
@EnableCaching(proxyTargetClass = true)
public class CacheConfig extends CachingConfigurerSupport {

    @Value("${spring.cache.redis.expire-time}")
    private Long cacheDefaultExpire;

    @Bean
    public CacheManagerCustomizer cacheManagerCustomizer() {
        return cacheManager -> {
            RedisCacheManager redisCacheManager = (RedisCacheManager) cacheManager;
            redisCacheManager.setDefaultExpiration(cacheDefaultExpire);
            redisCacheManager.setUsePrefix(true);
            redisCacheManager.setExpires(getCacheExpires());
        };
    }

    //配置缓存过期时间
    private Map<String, Long> getCacheExpires() {
        Map<String, Long> expires = new HashMap<>();

        //设置提交时间限制
//        expires.put(PropertyConstants.PROPERTY_CUSTOMER_BUY_HOUSE_CACHE_NAME, 60 * 5l);

        return expires;
    }

    @Bean
    public NumberGenerator numberGenerator(CacheManager cacheManager) {
        return new NumberGenerator(cacheManager);
    }

    @Bean
    public MethodInvokingFactoryBean repositoryHelperMethodInvokingFactoryBean(EntityManagerFactory entityManagerFactory) {
        MethodInvokingFactoryBean factoryBean = new MethodInvokingFactoryBean();
        factoryBean.setStaticMethod("com.rabbit.spring.data.repository.RepositoryHelper.setEntityManagerFactory");
        factoryBean.setArguments(entityManagerFactory);
        return factoryBean;
    }

}
